'''
* This is the projet for Brtc LlmOps Platform
* @Author Leon-liao <liaosiliang@alltman.com>
* @Description //TODO 
* @File: vector_database_service.py
* @Time: 2025/11/13
* @All Rights Reserve By Brtc
'''
import logging
from dataclasses import dataclass
from typing import Any
from flask import Flask
from flask_weaviate import FlaskWeaviate
from injector import inject
from langchain_core.documents import Document as LCDocument
from langchain_core.vectorstores import VectorStoreRetriever
from langchain_weaviate import WeaviateVectorStore
from weaviate.collections import Collection
from .embeddings_service import EmbeddingsService

COLLECTION_NAME = "brtc_weaviate_ai_store_1536"
@inject
@dataclass
class VectorDataBaseService:
    """向量数据库服务"""
    weaviate:FlaskWeaviate
    embeddings_service:EmbeddingsService

    async def _get_client(self,flask_app:Flask):
        with flask_app.app_context():
            return self.weaviate.client

    @property
    def vector_store(self)->WeaviateVectorStore:
        return WeaviateVectorStore(
            client=self.weaviate.client,
            index_name=COLLECTION_NAME,
            text_key="text",
            embedding=self.embeddings_service.cache_backed_embeddings,
        )


    def add_documents(self, documents: list[LCDocument], **kwargs:Any):
        """往向量数据库中新增文档, 将 vector_store 使用async 进行封装 防止在gevent 事件中出现循环错误"""
        logging.error("============================================================")
        self.vector_store.add_documents(documents, **kwargs)


    def get_retriever(self)->VectorStoreRetriever:
        """获取检索器"""
        return self.vector_store.as_retriever()


    @property
    def collection(self)->Collection:
        return self.weaviate.client.collections.get(COLLECTION_NAME)